#include "EC11.h"
#include "zf_gpio.h"

EC11_type EC11;

void EC11_Init(void)
{
    EC11.encoRealVal = 0;
    // 都设置为准双向口
    gpio_mode(P4_7, GPIO);
    gpio_mode(P1_0, GPIO);
    gpio_mode(P1_1, GPIO);
    // 设置4.1K内部电阻上拉
    gpio_pull_set(P4_7, PULLUP);
    gpio_pull_set(P1_0, PULLUP);
    gpio_pull_set(P1_1, PULLUP);
    // 设置初值
    EC11_BTN_Pin = TRUE;
    EC11_A_Pin = TRUE;
    EC11_B_Pin = TRUE;
    // 下降沿触发
    P1IM0 = 0x00;
    P1IM1 = 0x00;
    // 清除标志位并开启使能
    P1INTF = 0x00;
    P1INTE = 0x01;
}

uint8 EC11_Process(void)
{
    static bool PrevState, ClickState;

    if (!EC11_BTN_Pin)
    {
        if (PrevState)
        {
            EC11.btnSustainTime += BTN_SCAN_TIME;
            if (EC11.btnSustainTime >= BTN_LONG_CLICK_TIME)
            {
                ClickState = 0;
                // 长按
                EC11.btnSustainTime = 0;
                return BUTTON_LONG;
            }
            return BUTTON_NONE;
        }
        else
        {
            ClickState++;
            PrevState = TRUE;
            EC11.btnSpacingTime = 0;
            EC11.btnSustainTime = 0;
            return BUTTON_NONE;
        }
    }

    if (ClickState == 1)
    {
        if (EC11.btnSpacingTime >= BTN_DOUBLE_CLICK_TIME)
        {
            // 单击
            ClickState = 0;
            return BUTTON_CLICKED;
        }
    }
    else if (ClickState >= 2)
    {
        if (EC11.btnSpacingTime <= BTN_DOUBLE_CLICK_TIME)
        {
            // 双击
            ClickState = 0;
            return BUTTON_DOUBLE;
        }
    }

    EC11.btnSpacingTime += BTN_SCAN_TIME;
    PrevState = FALSE;
    return BUTTON_NONE;
}